<template>
  <t-form ref="form" :class="['item-container', `login-${type}`]" :data="formData" :rules="FORM_RULES" label-width="0"
          @submit="onSubmit">
    <template v-if="type == 'password'">
      <t-form-item name="account">
        <t-input v-model="formData.account" size="large" :placeholder="$t('login.login.pl.account')">
          <template #prefix-icon>
            <t-icon name="user"/>
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input v-model="formData.password" size="large" :type="showPsw ? 'text' : 'password'" clearable
                 :placeholder="$t('login.login.pl.password')">
          <template #prefix-icon>
            <t-icon name="lock-on"/>
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw"/>
          </template>
        </t-input>
      </t-form-item>

      <div class="check-container remember-pwd">
        <t-checkbox>{{ $t('login.login.rememberAccount') }}</t-checkbox>
        <span class="tip">{{ $t('login.login.forgotAccount') }}</span>
      </div>
    </template>

    <!-- 扫码登陆 -->
    <template v-else-if="type == 'qrcode'">
      <div class="tip-container">
        <span class="tip">{{ $t('login.login.scan.wechat') }}</span>
        <span class="refresh">{{ $t('common.refresh') }} <t-icon name="refresh"/> </span>
      </div>
      <qrcode-vue value="" :size="160" level="H"/>
    </template>

    <!-- 手机号登陆 -->
    <template v-else>
      <t-form-item name="phone">
        <t-input v-model="formData.phone" size="large" :placeholder="$t('login.login.pl.phone')">
          <template #prefix-icon>
            <t-icon name="mobile"/>
          </template>
        </t-input>
      </t-form-item>

      <t-form-item class="verification-code" name="verifyCode">
        <t-input v-model="formData.verifyCode" size="large" :placeholder="$t('login.login.pl.verificationCode')"/>
        <t-button size="large" variant="outline" :disabled="countDown > 0" @click="sendCode">
          {{
            countDown == 0 ? $t('login.login.button.sendVerification') : $t('login.login.pl.nRetry.sendVerification', [countDown])
          }}
        </t-button>
      </t-form-item>
    </template>
    <Verify
      @success="verifySuccess"
      mode="pop"
      captchaType="blockPuzzle"
      :imgSize="{ width: '330', height: '185' }"
      ref="verifyRef"
    ></Verify>
    <t-form-item v-if="type !== 'qrcode'" class="btn-container">
      <t-button block size="large" type="submit"> {{ $t('login.label.login') }}</t-button>
    </t-form-item>

    <div class="switch-container">
      <span v-if="type !== 'password'" class="tip"
            @click="switchType('password')">{{ $t('login.login.type.account') }}</span>
      <span v-if="type !== 'qrcode'" class="tip"
            @click="switchType('qrcode')">{{ $t('login.login.type.wechatScan') }}</span>
      <span v-if="type !== 'phone'" class="tip" @click="switchType('phone')">{{ $t('login.login.type.phone') }}</span>
    </div>
  </t-form>
</template>

<script setup lang="ts">
import QrcodeVue from 'qrcode.vue';
import type {FormInstanceFunctions, FormRule, SubmitContext} from 'tdesign-vue-next';
import {MessagePlugin} from 'tdesign-vue-next';
import {ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import Verify from './Verify.vue'
import {useCounter} from '@/hooks';
import {useUserStore} from '@/store';
import i18n from '@/i18n';

const userStore = useUserStore();

const INITIAL_DATA = {
  phone: '',
  account: 'admin',
  password: '123456',
  verifyCode: '',
  checked: false,
};

const FORM_RULES: Record<string, FormRule[]> = {
  phone: [{required: true, message: i18n.global.t('login.register.form.required.phone'), type: 'error'}],
  account: [{required: true, message: i18n.global.t('login.login.required.account'), type: 'error'}],
  password: [{required: true, message: i18n.global.t('login.register.form.required.password'), type: 'error'}],
  verifyCode: [{
    required: true,
    message: i18n.global.t('login.register.form.required.verificationCode'),
    type: 'error'
  }],
};

const type = ref('password');

const form = ref<FormInstanceFunctions>();
const formData = ref({...INITIAL_DATA});
const showPsw = ref(false);
const verifyRef = ref()
const [countDown, handleCounter] = useCounter();

const switchType = (val: string) => {
  type.value = val;
};

const router = useRouter();
const route = useRoute();

const verifySuccess = async (params: {captchaVerification:string}) => {
  Reflect.set(formData.value, 'captchaVerification',params.captchaVerification)
  await userStore.login(formData.value);
  MessagePlugin.success(i18n.global.t('login.login.message.success'));
  const redirect = route.query.redirect as string;
  const redirectUrl = redirect ? decodeURIComponent(redirect) : '/dashboard/index';
  router.push(redirectUrl);
}
const useVerify = () => {
  verifyRef.value.show()
}
/**
 * 发送验证码
 */
const sendCode = () => {
  form.value.validate({fields: ['phone']}).then((e) => {
    if (e === true) {
      handleCounter();
    }
  });
};

const onSubmit = async (ctx: SubmitContext) => {

  if (ctx.validateResult === true) {
    //点击登录调用验证码组件
    useVerify()

  }
};
</script>

<style lang="less" scoped>
@import url('../index.less');
</style>
